package cn.itsource.org.service.impl;

import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 事务acid
 *  1 原子性
 *  2 一致性：回滚-----在一个事务内报错看它是否回滚
 *  3 隔离性
 *  4 持续性
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService{

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    //Employee操作要同步操作logininfog
    @Transactional
    @Override
    public void add(Employee employee) {
        initEmployee(employee);// 处理密码和盐值等信息
        LoginInfo info= employee2LoginInfo(employee);
        loginInfoMapper.save(info);
        employee.setInfo(info);
        employeeMapper.save(employee);
    }

    private LoginInfo employee2LoginInfo(Employee employee) {
        LoginInfo info = new LoginInfo();
        BeanUtils.copyProperties(employee,info);
        info.setType(0); //0 是员工 1 用户
        return info;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String securityPwd = MD5Utils.encrypByMd5(employee.getPassword()+salt);

        employee.setSalt(salt);
        employee.setPassword(securityPwd);
    }

    @Transactional
    @Override
    public void del(Long id) {
        //通过员工id查询Employee进而获取loginInfoid
        Employee employee = employeeMapper.loadById(id);
        //删除loginInfo
        loginInfoMapper.remove(employee.getLogininfo_id());
        //删除员工
        employeeMapper.remove(id);
    }

    //@TODO 自己写
    @Transactional
    @Override
    public void update(Employee employee) {
        super.update(employee);
    }

    @Override
    public void bulkDel(List<Long> ids) {
        employeeMapper.bulkRemove(ids);
    }
}
